﻿using SmartHRMS.Infrastructure;
using SmartHRMS.Model.Company;
using System;

namespace SmartHRMS.Services
{
    public class CompanyService : ICompanyService
    {
        private ICompanyRepository _CompanyRepository;
        private IUnitOfWork _UnitOfWork;

        public CompanyService(ICompanyRepository CompanyProfileRepository, IUnitOfWork UnitOfWork)
        {
            this._CompanyRepository = CompanyProfileRepository;
            this._CompanyRepository.Inject(UnitOfWork);
            this._UnitOfWork = UnitOfWork;
        }

        #region ICompanyProfileService Members

        public Company LoadCompanyProfile()
        {
            return _CompanyRepository.LoadCompanyProfile();
        }

        public CompanyAddress LoadCompanyAddress(Guid companyId)
        {
            return _CompanyRepository.LoadCompanyAddress(companyId);
        }

        public void Save(Company company)
        {
            if (company.GetBrokenRules().Count > 0)
            {
                string brokenRules = BuildErrorListFrom(company);

                throw (new InvalidOperationException(string.Format("The Compnay information is not in a valid state to be persisted. {0}", brokenRules)));
            }
            else
            {
                _CompanyRepository.Save(company);               
                _UnitOfWork.Commit();
            }
        }

        private string BuildErrorListFrom(SmartHRMS.Model.Company.Company company)
        {
            System.Text.StringBuilder brokenRulesList = new System.Text.StringBuilder();

            foreach (BrokenRule brokenRule in company.GetBrokenRules())
            {
                brokenRulesList.Append(brokenRule.Rule);
                brokenRulesList.Append(Environment.NewLine);
            }

            return brokenRulesList.ToString();
        }
        #endregion
    }
}
